<template>
  <div>
      <div class="tabsBox d-flex m-b20">
          <div
                  class="tabsItem"
                  :class="item.id == state.tabId ? 'tabsItemHover' : ''"
                  v-for="item in tabsList"
                  :key="item.id"
                  @click="
        () => {
          state.tabId = item.id
          getTypeList()
        }
      "
          >
              {{ item.name }}
          </div>
      </div>
      <div class="tabsClass">
          <div class="treesty" v-if="false">
              <el-tabs
                      v-model="activeName"
                      v-loading="state.loading"
                      class="demo-tabs"
                      @tab-change="handleClick"
              >
                  <el-tab-pane label="组织架构" name="0"></el-tab-pane>
                  <el-tab-pane label="项目类型" name="1"></el-tab-pane>
              </el-tabs>
              <el-tree
                      :data="data"
                      :node-key="state.tabId2"
                      default-expand-all
                      :expand-on-click-node="false"
                      @node-click="handleNodeClick"
              >
                  <template #default="{ data }">
          <span class="custom-tree-node">
            <span>{{ data[state.tabName] }}</span>
          </span>
                  </template>
              </el-tree>
          </div>
          <div class="tabBox">
              <tableIndex
                      ref="tableindex"
                      :tableData="tableData"
                      :tableHead="tableHead"
                      :isIndex="false"
                      :isSelection="true"
                      :isRadio="false"
                      :fields="state.fields"
                      :height="500"
                      :page="page"
                      @selectChange="selectChange"
                      @searchList="searchList"
                      @page-change="pageChange"
              >
                  <template #isDark="{row}">
                        <span>{{row.$index + 1}}</span>
                        <svg-icon v-if="row.isDark===1" icon-class="openWire" class="m-l5" style="font-size: 16px;"></svg-icon>
                  </template>
                  <template #interestStatus="{ row }">
                      <svg-icon
                              v-if="row.interestStatus == 1"
                              icon-class="heart-active"
                      />
                      <svg-icon v-else icon-class="heart" />
                  </template>
                  <template #btns>
                      <div style="float: right">
                          <!-- <el-button
                            size="small"
                            plain
                            class="look"
                            @click="taskDistribution"
                            ><svg-icon icon-class="pf-task" /> 任务派发</el-button
                          > -->
<!--                          <el-button
                              v-if="state.tabId==='3'"
                              size="small"
                              plain
                              class="button_edit"
                              @click="changeDark"
                          >一键传暗</el-button
                          >-->
                          <el-button
                                  size="small"
                                  plain
                                  class="button_edit"
                                  @click="
                                    onExport({
                                      ...getSearchData(),
                                      type: state.tabId,
                                      prepareStatus: 1
                                    })
                                  "
                          ><svg-icon icon-class="export" /> 一键导出</el-button
                          >
                      </div>
                  </template>
                  <template #operate>
                      <el-table-column
                              label="操作"
                              width="300"
                              align="center"
                              fixed="right"
                      >
                          <template #default="{ row }">
                              <!-- <el-button
                                size="small"
                                class="end"
                                type="primary"
                                @click="statusChangeHandler(row)"
                                >状态变更</el-button
                              > -->
                              <!-- <el-button
                                size="small"
                                class="end"
                                type="primary"
                                @click="projectEditHandler(row)"
                                >编辑</el-button
                              >
                              <el-button
                                size="small"
                                class="look"
                                type="primary"
                                @click="lookHandler(row)"
                                >查看</el-button
                              > -->
                              <el-button
                                      v-if="state.tabId==='1'"
                                      size="small"
                                      class="button_edit m-b10"
                                      type="primary"
                                      @click="goPath(row)"
                              >查看</el-button
                              >
                              <el-button
                                  v-if="state.tabId==='3' && row.isGovernment === 1"
                                  size="small"
                                  class="button_edit m-b10"
                                  type="primary"
                                  @click="queryTaskNotification(row)"
                              >任务通知书</el-button
                              >
                              <el-button
                                      size="small"
                                      class="button_view m-b10"
                                      type="primary"
                                      @click="pushProjectPlan(row)"
                              >项目规划</el-button
                              >
                              <el-button
                                      size="small"
                                      type="primary"
                                      class="button_cancel m-b10"
                                      @click="projectKanBan(row)"
                              >项目看板</el-button
                              >
                                <el-button
                                v-if="state.tabId === '1' && row.projectTypeId==='1'"
                                size="small"
                                class="button_funtion m-b10"
                                type="primary"
                                @click="investmentPlan(row)"
                                >投资方案</el-button
                                >
                              <el-button
                                  v-if="state.tabId==='1' && row.isBack === 0"
                                  size="small"
                                  class="button_funtion m-b10"
                                  type="primary"
                                  @click="afterInvestment(row)"
                              >转为投后</el-button
                              >
                          </template>
                      </el-table-column>
                  </template>
                  <template #btn-add>
                      <div class="itemBtn" @click.prevent="radioChange">
                          <div
                                  class="screen-button d-flex a-center j-center"
                                  :style="{
										'--screen-button-border-color':
                    hiddenInterest ? '#fc7037' : '#CCCCCC',
									}"
                          >
                              <el-radio v-model="hiddenInterest" :label="true">
                                  隐藏未关注的项目
                              </el-radio>
                          </div>
                      </div>
                  </template>
              </tableIndex>
              <preliminaryCom ref="preliminary"></preliminaryCom>
              <!-- <projectStage ref="projectstage"></projectStage> -->
          </div>
      </div>
  </div>

    <!--	投资方案		-->
    <add-investment-projects
        ref="addInvestmentProjectsRef"
        title="投资方案"
        v-model:visible="addInvestmentProjectsVisible"
    />

    <task-notification-popup ref="taskNotificationPopupRef" :list="list"/>
</template>
<script setup>
import TableIndex from '@/components/table/index.vue'
import {ref, reactive, onMounted, onBeforeMount, watch, provide} from 'vue'
import PreliminaryCom from './components/status_change_dialog.vue'
import {ElDialog, ElTabPane, ElTabs, ElForm, ElFormItem, ElMessage, ElMessageBox} from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { projectConfigApi, department, publicProject } from '@/api/project.js'
import { deriveHandelFnc } from '@/hooks/downCommon'
import { projectInfoApi } from '@/api/biddingProject.js'
import SvgIcon from "@/components/SvgIcon/index.vue";
import AddInvestmentProjects from "@/views/constructionProjectManage/preliminaryProject/components/addInvestmentProjects.vue";
import {investmentDailyApi, reserveInvestmentProjectLibraryApi} from "@/api/investment";
import TaskNotificationPopup from "@/views/constructionProjectManage/project_mt/components/taskNotificationPopup.vue";

//路由跳转
let router = useRouter()
let tableindex = ref(null)
let activeName = ref('0')
let preliminary = ref(null)
let data = reactive([])
const list = ref([]);
const tabsList = ref([
  {
    name: '投资类',
    id: '1'
  },
  {
    name: '设计类',
    id: '2'
  },
  {
    name: '开发类',
    id: '3'
  },
  {
    name: '运营类',
    id: '4'
  },
  {
    name: '公共类',
    id: '5'
  }
])

let state = reactive({
  treeDepartmentId: '',
  tabId2: '1',
  tabId: '1',
  tabName: 'departmentName',
  loading: true,

  fields: [
    { key: 'projectQuery', label: '项目名称', type: 'input' },
    {
      key: 'projectSetId',
      label: '关联项目集',
      type: 'select',
      options: {
        list: []
      }
    },
    {
      key: 'streetCode',
      label: '项目位置',
      type: 'select',
      options: {
        list: []
      }
    },
    {
      key: 'year',
      label: '项目年份',
      type: 'year'
    },
    {
      key: 'departmentId',
      label: '立项部门',
      type: 'select',
      options: {
        list: []
      }
    },
    {
      key: 'status',
      label: '项目状态',
      type: 'select',
      options: {
        list: [
          {
            label: '全部',
            value: ''
          },
          {
            label: '未开工',
            value: -2
          },
          {
            label: '停工',
            value: -1
          },
          {
            label: '施工中',
            value: 1
          },
          {
            label: '竣工',
            value: 2
          },
          {
            label: '其他',
            value: 3
          }
        ]
      }
    },
    {
      key: 'projectTypeId',
      label: '项目分类',
      type: 'select',
      options: {
        list: []
      }
    },
      {
          key: 'isGovernment',
          label: '政府项目',
          type: 'select',
          options: {
              list: [
                  {
                      label: '全部',
                      value: ''
                  },
                  {
                      label: '否',
                      value: 0
                  },
                  {
                      label: '是',
                      value: 1
                  }
              ]
          }
      },
  ],
  partnerList:[],
  row:null,
  title:'新增',
})

provide('state', state);

const formInline = reactive({
  user: '',
  region: '',
  date: [],
  radio: 0
})

const page = reactive({
  page: 1,
  pageSize: 50,
  total: 0
})

const getLocations = () => {
  projectInfoApi.getLocations(2, '').then((res) => {
    if (res.code == 200) {
      state.fields[2].options.list = res.data.map((v) => {
        return {
          label: v.name,
          value: v.code
        }
      })
    }
  })
}

/**
 * 合作方
 */
const getAllPartner = () => {
    reserveInvestmentProjectLibraryApi.getAllPartner().then(res=>{
        const {code,data} = res;
        if(code === '200'){
            state.partnerList = data;
        }
    });
}


// --------------
// table相关
//获取部门信息
const getdepartmentList = () => {
  department.getProjectPhase().then((res) => {
    if (res.code == 200) {
      data = res.data
      state.loading = false
    }
    // console.log('----------------', data);
  })
}
// 获取项目子类
const getTypeList = () => {
  projectConfigApi.getTypeList('10' + state.tabId).then((res) => {
    state.fields[6].options.list = []
    if (res.code == 200) {
      res.data.map((v) => {
        state.fields[6].options.list.push({
          value: v.projectTypeId,
          label: v.typeName
        })
      })
    }
  })
}
const handleClick = (e) => {
  // console.log('00000', activeName);
  switch (activeName.value) {
    case '0':
      state.loading = true
      getdepartmentList()
      state.tabId2 = 'departmentId'
      state.tabName = 'departmentName'
      break
    case '1':
      state.loading = true
      publicProjectData()
      state.tabId2 = 'projectTypeId'
      state.tabName = 'typeName'
      break
    default:
      break
  }
}

let tableHead = reactive([
  // {
  // 	prop: "interestStatus",
  // 	label: "关注",
  // 	isSvg: ["gz_true", "gz_false"],
  // },
    {
        prop: 'isDark',
        label: '序号',
        slot: 'isDark'
    },
  {
    prop: 'interestStatus',
    label: '重点关注',
    slot: 'interestStatus'
  },
  {
    prop: 'projectName',
    label: '项目名称',
    width: '120',
    style: {
      color: '#FC7018'
    }
  },
  // {
  //   prop: 'projectId',
  //   label: '项目编号'
  // },
  {
    prop: 'streetName',
    label: '项目位置'
  },
  {
    prop: 'projectTypeName',
    label: '项目分类'
  },
    {
    prop: 'isGovernment',
    label: '政府项目',
    formatter: (row) => {
        if(row.isGovernment!==null){
            return ['否','是'][row.isGovernment]
        }
        return '-';
    },
  },
  {
    prop: 'responsibleDepartmentName',
    label: '项目立项部门',
    minWidth: 120,
  },
  {
    prop: 'projectAmount',
    label: '拟计划总投额',
    minWidth: 120,
  },
  {
    prop: 'realProjectAmount',
    label: '实际总投额',
    formatter: (row) => {
      return row.realProjectAmount ? row.realProjectAmount : '0'
    },
    minWidth: 100,
  },
  {
    prop: 'createTime',
    label: '项目创建时间',
    minWidth: 120,
  },
  {
    // -2未开工-1停工1施工中2竣工3其他
    prop: 'status',
    label: '项目状态',
    formatter: (row) => {
      let str = ''
      switch (row.status) {
        case -2:
          str = '未开始'
          break
        case -1:
          str = '停工'
          break
        case 1:
          str = '进行中'
          break
        case 2:
          str = '已完成'
          break
        case 3:
          str = '其他'
          break
      }
      return str
    }
  }
])
let tableData = ref([])

//获取搜索组件数据
const getSearchData = () => {
  return tableindex.value.getSearchData()
}
//获取项目类型
const publicProjectData = () => {
  publicProject.getProjectTypeTreeVo().then((res) => {
    if (res.code == 200) {
      data = res.data
      state.loading = false
    }
  })
}
//项目状态变更
const statusChangeHandler = (row) => {
  preliminary.value.state.centerDialogVisible = true
}

//项目编辑
const projectEditHandler = (row) => {
  router.push({
    path: `/constructionProjectManage/project_mt/components/projectInfo/type=${1}&id=${
      row?.projectId || ''
    }`
  })
}
//项目阶段修改
const pushProjectPlan = (row) => {
  router.push({
    path: `/constructionProjectManage/projectPlan/index/tabId=${state.tabId}&type=${1}&id=${
      row?.projectId || ''
    }&isDark=${row.isDark}`
  })
}

//项目看板
const projectKanBan = (row) => {
  router.push({
    path: `/constructionProjectManage/projectsPectaculars/pectaculars/type=${1}&id=${
      row?.projectId || ''
    }&name=${row?.projectName || ''}&projectType=${state.tabId}&tabId=${state.tabId}&isDark=${row.isDark}&isGovernment=${row.isGovernment}&isPresetPlan=0`
  })
}

//项目查看
const lookHandler = (row) => {
  router.push({
    path: `/constructionProjectManage/project_mt/components/lookProjectInfoAll/type=1&id=${row.projectId}&projectType=${state.tabId}`
  })
}
// 获取项目集
const getpublicProject = () => {
  projectConfigApi.getProjectSets().then((res) => {
    if (res.code == 200) {
      res.data.forEach((item) => {
        state.fields[1].options.list.push({
          label: item.projectSetName,
          value: item.projectSetId
        })
      })
    }
  })
}
// 获取部门
const getAllDepartments = () => {
  department.getAllDepartments().then((res) => {
    if (res.code == 200) {
      res.data.forEach((item) => {
        state.fields[4].options.list.push({
          label: item.departmentName,
          value: item.departmentId
        })
      })
    }
  })
}
//搜索查询
const searchList = (e) => {
  if (state.treeDepartmentId) {
    e.departmentId = state.treeDepartmentId
  }
  getPage(e)
}
//分页
const pageChange = (e) => {
  page.page = e.page
  page.pageSize = e.limit

  getPage()
}

watch(
  () => state.tabId,
  () => {
    getPage(getSearchData())
  }
)

let hiddenInterest = ref(false);
let radioChange = () => {
  if (hiddenInterest.value) {
		hiddenInterest.value = false;
	} else {
		hiddenInterest.value = true;
  }
  getPage({
    hiddenInterest: hiddenInterest.value
  })
}

const getPage = (e) => {
  let data = {
    pageNum: page.page,
    pageSize: page.pageSize,
    param: {
      ...e,
      prepareStatus: 1,
      type: state.tabId,
      ...getSearchData()
    }
  }
  projectConfigApi.getProjectPage(data).then((res) => {
    if (res.code == 200) {
      tableData.value = res.data.content
      page.total = res.data.totalSize
      // console.log(tableData);
    }
  })
}

const exportConfig = reactive({
  fileName: '正式项目管理',
  apiPath: 'projectExport',
  form: {}
})
const { onExport } = deriveHandelFnc(exportConfig)

const selectProjectList = ref([]);
const selectChange = (e) => {
  selectProjectList.value = e;
}

/**
 * 查看
 */
const goPath = (row) => {
    router.push({path:`/constructionProjectManage/invest/details/${row.projectId}/${row.projectTypeId}/1`});
}

/**
 * 任务通知书
 */
const taskNotificationPopupRef = ref(null);
const queryTaskNotification = (row) => {
    projectConfigApi.governmentFiles({projectId:row.projectId}).then(res=>{
        if(res.code==='200'){
            list.value = res.data;
            taskNotificationPopupRef.value.handleOpen();
        }
    });
};

/**
 * 一键转暗
 */
const changeDark = () => {
    if(selectProjectList.value.length===0){
        return ElMessage.warning('请选择需要转暗的数据!');
    }
    ElMessageBox.confirm(
        '确认一键转暗吗?',
        '提示',
        {
            distinguishCancelAndClose: true,
            confirmButtonText: '确认',
            cancelButtonText: '取消',
        }
    )
        .then((action)=>{
            if(action==='confirm'){
                let projectIds = selectProjectList.value.map((item)=>{return item.projectId});
                projectConfigApi.createDarkProject({projectIds:projectIds}).then(res=>{
                    if(res.code==='200'){
                        ElMessage.success('操作成功!');
                        getPage()
                    }else{
                        ElMessage.error('操作失败!');
                    }
                });
            }
        });
}

const addInvestmentProjectsVisible = ref(false);
/**
 * 投资方案
 */
const addInvestmentProjectsRef = ref(null);
const investmentPlan = (row) => {
    state.row = row;
    addInvestmentProjectsVisible.value = true;
    addInvestmentProjectsRef.value.getStatus(row.projectId);
}

/**
 * 转为投后
 */
const afterInvestment = (row) => {
    investmentDailyApi.turnBack({projectId:row.projectId }).then(res=>{
        if(res.code==='200'){
            ElMessage.success('项目转变成功!');
            getPage();
        }
    });
}

onBeforeMount(() => {
  getdepartmentList()
})
onMounted(() => {
  getPage()
  getpublicProject()
  getAllDepartments()
  getTypeList()
  getLocations()
  getAllPartner();
})
</script>
<style lang="scss" scoped>
@import '@/views/constructionProjectManage/static/button.scss';
.tabsClass {
  display: flex;
  .treesty {
    width: 13%;

    margin-right: 10px;
    .demo-tabs {
      width: 100%;
    }
    .el-tree {
      overflow-y: scroll;
      height: 500px;
    }
  }
  .tabBox {
    width: 100%;
  }
}
.tabsBox {
  margin-bottom: 30px;
  .tabsItem {
    padding: 0 30px;
    text-align: center;
    line-height: 40px;
    height: 40px;
    border: 1px solid #ccc;
    margin-right: 20px;
    color: #ccc;
    border-radius: 5px;
    cursor: pointer;
  }
  .tabsItemHover {
    border: 1px solid #fc702b;
    color: #fc702b;
    background: #fff8f6;
  }
}
:deep(.el-date-editor--year) {
  height: 40px;
  .el-input__wrapper {
    height: 40px;
  }
}
@import '@/assets/general_style/dialog.scss';
</style>
